import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, Select, Table, Tag, Tooltip } from 'antd';
import dayjs from 'dayjs';

import { drawMap } from '@/components/canvasRecord/drawMap';
import Filter from '@/components/filter';
import Text from '@/components/text';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import { proInspectionRecordPagePoint } from '@/services/bizApi/shengchanxunjianjilujiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProInspectionPointRecordEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await proInspectionRecordPagePoint({
        ...formData,
        ...id,
        deliveryTimeBegin: formData.deliveryDate
          ? dayjs(formData.deliveryDate?.[0]).format('YYYY-MM-DD')
          : undefined,
        deliveryTimeEnd: formData.deliveryDate
          ? dayjs(formData.deliveryDate?.[1]).format('YYYY-MM-DD')
          : undefined,
        reportTimeBegin: formData.reportDate
          ? dayjs(formData.reportDate?.[0]).format('YYYY-MM-DD')
          : undefined,
        reportTimeEnd: formData.reportDate
          ? dayjs(formData.reportDate?.[1]).format('YYYY-MM-DD')
          : undefined,
        normal: false,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter} extra={<></>}>
        <Filter.Item name="pointName">
          <Select
            style={{
              width: 180
            }}
            placeholder="异常点位"
            options={drawMap.map((item) => ({
              value: item.name,
              label: item.name
            }))}
          />
        </Filter.Item>
        <ProFormSelect
          name="abnormalHandleUserId"
          style={{ width: 180 }}
          label=""
          placeholder="请选择异常处理人"
          showSearch={true}
          request={async () => {
            const res = await orgUserInfoVoPage({
              page: 1,
              size: 1000
            });
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <ProFormSelect
          name="inspectionUserId"
          style={{ width: 180 }}
          label=""
          placeholder="请选择巡检人员"
          showSearch={true}
          request={async () => {
            const res = await orgUserInfoVoPage({
              page: 1,
              size: 1000
            });
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <Filter.Item name="abnormalHandleStatus">
          <Select style={{ width: 180 }} placeholder="异常处理状态">
            <Select.Option value={3}>已处理</Select.Option>
            <Select.Option value={1}>未处理</Select.Option>
          </Select>
        </Filter.Item>
        {/* <Filter.Item name="deliveryDate">
          <DatePicker.RangePicker placeholder={['上报时间', '上报时间']} />
        </Filter.Item> */}

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, row, index) => index + 1
          },
          {
            title: '异常点位',
            dataIndex: 'pointName'
          },
          {
            title: '异常描述',
            dataIndex: 'inspectionDesc'
          },
          {
            title: '上报时间',
            dataIndex: 'inspectionStartTime',
            render: (text, row) => <div>{dayjs(text).format('YYYY-MM-DD')}</div>
          },
          {
            title: '异常处理人',
            dataIndex: 'abnormalHandleUserName'
          },
          {
            title: '巡检人员',
            dataIndex: 'inspectionUserName'
          },
          {
            title: '处理状态',
            dataIndex: 'abnormalHandleStatus',
            render: (text, _row) =>
              text == 1 ? <Tag color="red"> 未处理</Tag> : <Tag color="green"> 已处理</Tag>
          },
          {
            title: '处理结果',
            dataIndex: 'abnormalHandleResult',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip placement="top" title={text} arrow={true}>
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && row.abnormalHandleStatus === 3 && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          rowData: row,
                          type: 'detail'
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}
                  {permission.check() && row.abnormalHandleStatus === 1 && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          rowData: row,
                          type: 'edit',
                          onSuccess: () => {
                            onSearch();
                          }
                        });
                      }}
                      type="primary"
                    >
                      处理
                    </Text>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
    </>
  );
};

export default Page;
